package com.ruoyi.system.chat.netty;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.Set;
import java.util.Map;

/**
 * 群聊分组管理器
 */
public class GroupChatManager {
    // clubId -> Set<Channel>
    private static final Map<Long, Set<Channel>> groupChannels = new ConcurrentHashMap<>();

    public static void addChannel(Long clubId, Channel channel) {
        groupChannels.computeIfAbsent(clubId, k -> new CopyOnWriteArraySet<>()).add(channel);
    }

    public static void removeChannel(Long clubId, Channel channel) {
        Set<Channel> set = groupChannels.get(clubId);
        if (set != null) {
            set.remove(channel);
            if (set.isEmpty()) {
                groupChannels.remove(clubId);
            }
        }
    }

    public static void broadcast(Long clubId, String message) {
        try {
            System.out.println("Broadcasting message to club " + clubId + ": " + message);
            Set<Channel> set = groupChannels.get(clubId);
            if (set != null) {
                System.out.println("Found " + set.size() + " channels for club " + clubId);
                for (Channel ch : set) {
                    if (ch.isActive()) {
                        try {
                            ch.writeAndFlush(new TextWebSocketFrame(message));
                            System.out.println("Message sent to channel: " + ch.id());
                        } catch (Exception e) {
                            System.err.println("Error sending message to channel " + ch.id() + ": " + e.getMessage());
                        }
                    } else {
                        System.out.println("Channel " + ch.id() + " is not active, removing from group");
                        set.remove(ch);
                    }
                }
            } else {
                System.out.println("No channels found for club " + clubId);
            }
        } catch (Exception e) {
            System.err.println("Error in broadcast: " + e.getMessage());
            e.printStackTrace();
        }
    }
} 